package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.DishNullException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Override
    @ApiOperation(value = "新增菜品")
    @Transactional
    public void save(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        //1.先插入菜品表
        dish.setCreateTime(LocalDateTime.now());
        dish.setUpdateTime(LocalDateTime.now());
        dish.setCreateUser(BaseContext.getCurrentId());
        dish.setUpdateUser(BaseContext.getCurrentId());
        dishMapper.insert(dish);
        //2.再插入菜品口味表
        Long dishId = dish.getId();
        List<DishFlavor> flavors = dishDTO.getFlavors();
        //判断菜品口味是否为空，不为空则遍历添加
        if(flavors != null && flavors.size() > 0){
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
            });
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    @Override
    @ApiOperation(value = "菜品分页查询")
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        Page<DishVO> page=dishMapper.pageQuery(dishPageQueryDTO);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    @ApiOperation(value = "菜品批量删除")
    public void deleteById(List<Long> ids) {
        //先判断菜品表是否有该菜品
        //1.根据id查询菜品表，判断是否为空
        //使用增强for循环遍历
        for (Long id : ids) {
            Dish dish = dishMapper.getById(id);
            if(dish == null){
                //2.如果为空，抛出异常
                throw new DishNullException(MessageConstant.DIDH_NULL);
            }
            //3.如果不为空，还要判断该菜品是否处于启售状态
            if(dish.getStatus() == 1){
                //4.如果处于启售状态，则抛出异常
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        //判断菜品是否关联了套餐
        List<Long> setmealIds =setmealDishMapper.checkExist(ids);
        if (setmealIds != null && setmealIds.size() > 0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        for (int i = 0; i < ids.size(); i++) {
            //5.如果未关联套餐，则删除菜品表和菜品口味表
            dishMapper.deleteById(ids.get(i));
            dishFlavorMapper.deleteByDishId(ids.get(i));
        }
    }

    @ApiOperation(value = "根据id查询菜品和关联的信息")
    @Override
    public DishVO getByIdWithFlavor(Long id) {
        Dish dish = dishMapper.getById(id);
        if (dish != null){
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(dish,dishVO);
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(id);
            dishVO.setFlavors(flavors);
            return dishVO;
        }
        return null;
    }

    @Override
    @ApiOperation(value = "修改菜品")
    public void update(DishDTO dishDTO) {
        //1.先向数据库查询菜品表，判断是否为空
        Dish dish = dishMapper.getById(dishDTO.getId());
        //2.如果不为空，再判断是否处于启售状态
        if (dish==null){
            throw new DishNullException(MessageConstant.DIDH_NULL);
        }
        //3.如果处于启售状态，则抛出异常
        if (dish.getStatus()==1){
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }
        //4.如果不处于启售状态，则修改菜品表和菜品口味表
        Dish dish1 = new Dish();
        dish1.setUpdateTime(LocalDateTime.now());
        dish1.setUpdateUser(BaseContext.getCurrentId());
        BeanUtils.copyProperties(dishDTO,dish1);
        dishMapper.updateDish(dish1);
        //5.删除菜品口味表
        dishFlavorMapper.deleteByDishId(dishDTO.getId());
        //6.添加菜品口味表
         List<DishFlavor> flavors = dishDTO.getFlavors();
         if (flavors != null && flavors.size() > 0){
             flavors.forEach(dishFlavor -> {
                 dishFlavor.setDishId(dishDTO.getId());
             });
             dishFlavorMapper.insertBatch(flavors);
         }
    }

    @Override
    @ApiOperation(value = "修改菜品的起售状态")
    public void startOrStop(Integer status, Long id) {
        //1.先判断菜品是否为空
        Dish dish = dishMapper.getById(id);
        //2.如果为空，抛出异常
        if (dish == null){
            throw new DishNullException(MessageConstant.DIDH_NULL);
        }
        //3.如果不为空，则修改菜品表
        //3.1 判断状态是否为1，如果是1，则修改为0，否则修改为1
        dish.setStatus(status);
        //3.2 修改时间
        dish.setUpdateTime(LocalDateTime.now());
        //3.3 修改人
        dish.setUpdateUser(BaseContext.getCurrentId());
        //3.4 修改状态
        dishMapper.updateDish(dish);

    }

    @Override
    @ApiOperation(value = "根据分类id查询菜品")
    public List<Dish> list(Long categoryId) {
        Dish dish=Dish.builder().categoryId(categoryId).status(StatusConstant.ENABLE).build();
        return dishMapper.list(dish);
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
